//
//  LiuiuCoreData.m
//  SnailPost
//
//  Created by Liuiu on 16/3/16.
//  Copyright © 2016年 抠泥ser. All rights reserved.
//

#import "LiuiuCoreData.h"
#import "VideoModel.h"
#import "Entity.h"

@implementation LiuiuCoreData

+(LiuiuCoreData *)defaultsCoreDataManager
{
    //防止多个线程同时执行下面代码 导致创建多个对象
    static LiuiuCoreData *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[LiuiuCoreData alloc] init];
    });
    return manager;
}

- (void)nslogCoreDataPath{
    NSLog(@"path%@",[self applicationDocumentsDirectory]);
}

- (void)addWithModelTitle:(NSString *)title cover:(NSString *)cover length:(NSNumber* )length playCount:(NSNumber *)playCount mp4_url:(NSString *)mp4_url
{
    //创建实体描述: 参数1描述的实体 参数2数据管理器
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:self.managedObjectContext];
    //创建实体: 参数1实体描述 参数2数据管理器
   
    Entity *video =[[Entity alloc]initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
    video.title = title;
    video.cover = cover;
    video.length = length;
    video.playCount = playCount;
    video.mp4_url = mp4_url;

    //保存数据
    [self saveContext];
    
    NSLog(@"插入数据成功");

}
-(NSArray *)selectModelWithKey:(NSString *)key value:(NSString *)value{
    //获取查询数据的请求 相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Entity"];
    //添加一个约束 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", key, @"%@"], value];
    //设置谓词
    request.predicate = predicate;
    
    //数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    //判断错误
    NSError *error;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (!error) {
        if (array.count != 0) {
            NSLog(@"查询成功:数据个数为%ld", array.count);
        }else{
            return 0;
        }
        return array;
    }else{
        NSLog(@"数据查询失败");
        return 0;
    }
}
-(NSArray *)selectAllModel{
    //获取查询数据的请求 相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Entity"];
    //判断错误
    NSError *error;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (!error) {
        if (array.count != 0) {
            NSLog(@"查询成功:数据个数为%ld", array.count);
        }else{
            NSLog(@"查询成功:数据个数为0");
        }
        return array;
    }else{
        NSLog(@"数据查询失败");
        return nil;
    }
}

-(void)updateModelWithKey:(NSString *)key value:(NSString *)value newValue:(NSString *)newValue{
    //获取查询数据的请求 相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Entity"];
    //添加一个约束 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", key, @"%@"], value];
    //设置谓词
    request.predicate = predicate;
    
    //数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    //判断错误
    NSError *error;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    
    //修改
    if (!error) {
        if (array.count != 0) {
            for (Entity *video in array) {
               video.title = newValue;
            }
            NSLog(@"数据更新成功");
        }else{
            NSLog(@"暂无更新数据");
        }
    }else{
        NSLog(@"数据更新失败");
    }
    
    //保存数据
    [self saveContext];
}

-(void)deleteModelWithKey:(NSString *)key value:(NSString *)value{
    //获取查询数据的请求 相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Entity"];
    //添加一个约束 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", key, @"%@"], value];
    //设置谓词
    request.predicate = predicate;
    
    //数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    //判断错误
    NSError *error;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    
    if (!error) {
        if (array.count != 0) {
            for (Entity *video in array) {
                [self.managedObjectContext deleteObject:video];
            }
            [self saveContext];
            NSLog(@"数据删除成功");
        }else{
            NSLog(@"暂无删除数据");
        }
    }else{
        NSLog(@"数据删除失败");
    }
}






#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "drf.Coredata" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Coredata.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


@end
